#include "CFramework.h"
#include "CGraphics.h"
#include "CBaseApp.h"
#include "CTimer.h"


CFramework::CFramework( CBaseApp* pGameApp )
{
}


CFramework::~CFramework(void)
{
}

void CFramework::OnUpdateFrame(void)
{
	if ( m_pTimer )
	{
		m_pTimer->Update();
	}
	if ( m_pGameApp != NULL && m_pGraphics != NULL && m_pTimer != NULL )
	{
		float elapsedTime = m_pTimer->GetElapsedTime();

		// Send out input data
		m_mouse.Read();
		m_keyboard.Read();
		long xDelta = m_mouse.GetXDelta();
		long yDelta = m_mouse.GetYDelta();
		long zDelta = m_mouse.GetZDelta();

		BOOL* pMouseButtons = m_mouse.GetButtons();
		BOOL* pPressedKeys = m_keyboard.GetKeys();
		m_pGameApp->ProcessInput( xDelta, yDelta, zDelta, pMouseButtons, pPressedKeys, elapsedTime );

		// Send out OnUpdateFrame
		m_pGameApp->OnUpdateFrame( m_pGraphics->GetDevice(), elapsedTime ); // pDevice
	}
}

void CFramework::OnRenderFrame(void)
{

}

LRESULT CALLBACK CFramework::StaticWndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
	if( msg = WM_CREATE )
	{
		SetWindowLongPtr( hWnd, GWLP_USERDATA, (LONG)((CREATESTRUCT *)lParam)->lpCreateParams );
	}

	CFramework *targetApp = (CFramework*)GetWindowLongPtr( hWnd, GWLP_USERDATA );

	if( targetApp )
	{
		return targetApp->WndProc( hWnd, msg, wParam, lParam );
	}

	return DefWindowProc( hWnd, msg, wParam, lParam );
}

LRESULT CALLBACK CFramework::WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
{
	switch ( message )
	{
		case WM_DESTROY:
			PostQuitMessage( 0 );
			return 0;
		case WM_PAINT:
			if ( m_pGraphics->GetDevice() )
			{
				OnUpdateFrame();
				OnRenderFrame();
			}
			ValidateRect( hWnd, 0 );
			return 0;
		case WM_SIZE:
			if ( wParam == SIZE_MINIMIZED )
			{
				m_active = FALSE;
			}
			else
			{
				m_active = TRUE;
				m_windowWidth = LOWORD( lParam );
				m_windowHeight = LOWORD( lParam );
				if ( m_pGraphics->GetDevice() )
				{
					OnLostDevice();
					m_pGraphics->Reset();
					OnResetDevice();
					OnUpdateFrame();
					OnRenderFrame();
				}
			}
			return 0;
	}
	return DefWindowProc( hWnd, message, wParam, lParam );
}

BOOL CFramework::Initialize( char* title, HINSTANCE hInstance, int width, int height, BOOL windowed )
{
	m_hInstance = hInstance;
	m_windowWidth = width;
	m_windowHeight = height;

	//Define the window
	WNDCLASSEX wcex;
	wcex.cbSize			=	sizeof ( WNDCLASSEX );
	wcex.style			=	CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc	=	WndProc;


}
